package com.xy.iot.controller;

import com.alibaba.fastjson.JSONObject;
import com.xy.iot.common.result.R;
import com.xy.iot.common.result.message.JSONMessageData;
import com.xy.iot.common.utils.CacheUtils;
import com.xy.iot.netty.device.DeviceServerChannel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * 设备相关控制的接口
 */
@Slf4j
@RestController
@RequestMapping("api/device/")
public class DeviceController {
    /**
     * 在线设备列表
     * onLine
     * @return
     */
    @RequestMapping("onLineList")
    public R onLineList() {
        return R.ok(CacheUtils.getAllKey());
    }

    /**
     * 向设备发送数据
     * @param sendData
     * @param key
     * @return
     */
    @PostMapping("sendData")
    public R sendData(
            @RequestParam(name = "sendData") String sendData,
            @RequestParam(name = "key") String key
    ) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("msg", sendData);
        log.info("key:{}，sendData：{}",key,sendData);
        Object data = CacheUtils.get(key);
        if (data != null){
            log.info("CacheData：{}",data.getClass().getSimpleName());
            if (data instanceof DeviceServerChannel){
                JSONMessageData asciiMessageData = new JSONMessageData();
                asciiMessageData.setCommandData(jsonObject);
                ((DeviceServerChannel) data).send(asciiMessageData);
                return R.ok("发送成功");
            }else {
                return R.error("CacheData格式错误："+data.getClass().getSimpleName());
            }
        }else {
            return R.error("设备不存在："+key);
        }
    }
}
